export default defineNuxtRouteMiddleware(async (to, from) => {
  // 登录和注册页面不进行登录状态校验
  if (to.path === "/user/login" || to.path === "/user/signUp") {
    return;
  }
  const currentUserStore = useCurrentUserStore();
  const token = useCookie("token");
  const cookie = useRequestHeader("cookie") as string;

  // token 不存在,则跳转到登录页面
  if (!token.value) {
    return navigateTo("/user/login");
  }
  // token 存在 + 用户没有登录，则重新获取当前登录用户数据
  if (
    token.value &&
    currentUserStore.currentUser &&
    !currentUserStore.currentUser.isLogin
  ) {
    const { data, error } = await useFetch("/api/user/current", {
      headers: { cookie, accept: "application/json" },
    });
    if (!error.value) {
      currentUserStore.setCurrentUser({
        isLogin: true,
        ...data.value,
      });
    } else {
      currentUserStore.setCurrentUser({
        isLogin: false,
      });
      token.value = null;
      navigateTo("/user/login");
    }
  }
});
